jQuery(document.body).ready(function ($) {

	//焦点图动画
	(function ($) {
		var DOM = $("#focusPic");
		var prev = $('.prev', DOM);
		var next = $('.next', DOM);
		var UL = $('#picList', DOM);
		var _container = UL[0].parentNode;
		var list = $('>li', UL);
		var cloneNode = $(list[0]).clone();
		UL.append(cloneNode);
		list = $('>li', UL);
		var _lock = false;
		_container.style.width = (list.length * 252) + "px";
		/**
		 * 移动至某个方向
		 * @param obj 列表ul元素
		 * @param direction 方向，1-左，2-右
		 */
		var moveTo = function (obj, direction) {
			if (_lock) return;
			_lock = true;
			var left = obj.position().left;
			if (direction) {
				if (Math.abs(left) >= obj.width() - 252) {
					left = 0;
					obj.css({left:left + "px"});
				}
				left -= 252;
			} else {
				if (left >= 0) {
					left = -(obj.width() - 252);
					obj.css({left:left + "px"});
				}
				left += 252
			}
			obj.animate({left:(left) + "px"}, 500, undefined, function () {
				_lock = false;
			});
		};
		prev.click(function () {
			moveTo(UL, 1);
		});
		next.click(function () {
			moveTo(UL, 0);
		});
	})($);

	var dialog;
	var refreshBtns = function(rows){
		rows = rows || dialog.find(".tbody>ul.tr");
		$(rows).each(function(i, row){
			var _upBtn = $(this).find(".arrow1_up");
			var _downBtn = $(this).find(".arrow1_down");
			_upBtn.show();
			_downBtn.show();
			$(row).find(".input_text").val("");
			$(row).find(".edit").show();
			if($(this).parent().children().first()[0] == $(this)[0]){
				_upBtn.hide();
			}else if ($(this).parent().children().last()[0] == $(this)[0]){
				_downBtn.hide();
			}
		});
	};
	var moveTo = function(thisObj, uOrD){
		var _thisRow = thisObj.parents("ul");
		var _otherRow = uOrD ? _thisRow.prev() : _thisRow.next();
		if(_otherRow){
			uOrD ? _thisRow.after(_otherRow) : _thisRow.before(_otherRow);
		}
		refreshBtns([_thisRow, _otherRow]);
	};
	var validator = {
		validStatus : false,
		run : function(){
			var me = this;
			$("#dialogForm").validator({
				"effect":"event",
				"inputEvent":"blur",
				"errorInputEvent":null,
				"lang" : "zh",
				"onBeforeValidate": function(){
				    me.validStatus = true;
				},
				"onSuccess" : function(){
					me.validStatus = false;
				}
			});
		},
		addNewRule : function(){
			$.tools.validator.localize("zh", {
					":url":"输入正确的url",
					":tagName":"输入正确的名称"
				}
			);
			$.tools.validator.addEffect("event", function(errs){
				$.each(errs,function(i, err){
					var input = err.input;
					var errTip = input.parents("ul").find(".color_red");
					errTip.show().html(err.messages[0]);
					setTimeout(function (){
					    input.show().focus();
                        input.prev().hide();
					}, 10);
				});
			}, function (input, event) {
				var txtNode = input.prev();
				txtNode.html(input.val()).show();
				input.hide();
				var ul = input.parents("ul");
				var errTip = ul.find(".color_red");
				errTip.hide();
				ul.find(".edit").show();
			});
			$.tools.validator.fn("[min-length]", function(input, value) {
			    var min = input.attr("min-length");
				var str = "";
				switch (input.attr("name")){
					case "url":
						str = "地址太短"
						break;
					case "tagName":
						str = "名称字符太少";
						break;
					default :
						str = "地址太短";
				}
			    return value.length >= min ? true : {
			        zh: str
			    };
		    });
			$.tools.validator.fn("[min-length]", function(input, value) {
			    var max = input.attr("max-length");
			    return $.byteLength(value) <= max ? true : {
			        zh: "最多允许 " + max + " 个字符或者 " + max/2 + " 个汉字"
			    };
		    });
			$.tools.validator.fn('[name="tname"]', function(input, value) {
				var min = 1;
			    return 0 >= min ? true : {
			        zh: "地址太短"
			    };
		    });
		},
		checkValid : function(){
			return this.validStatus;
		}
	};
	var templateAndFuns = {
		focusPic : {
			template : '<form id="dialogForm" novalidate="novalidate"> <div class="inner"><a class="close" actname="close" href="javascript:void(0);" title="关闭">×</a> <div class="title"><strong>活动管理</strong></div> <!--弹层内容--> <div class="wrap"> <div class="tablebox table2"> <div class="thead"> <ul class="tr"> <li class="td_width1">活动地址</li> <li class="td_width3">展示位置</li> </ul> </div> <div class="tbody"> <ul class="tr"> <li class="td_width1"><span class="content">aaa.com</span><input style="display:none;" name="url" id="" class="input_text" min-length="4" type="url"> </li> <li class="td_width2"><span class="color_red" style="display: none;"></span> <span class="edit hover"><a href="javascript:void(0);" actname="edit"><i class="icon_edit"></i>编辑标签</a><a actname="delete" href="javascript:void(0);"><i class="icon_del"></i>删除标签</a></span></li> <li class="td_width3"><a href="javascript:void(0);" class="arrow1_up" actname="moveUp" title="上移" style="display: none;"></a> <a href="javascript:void(0);" actname="moveDown" class="arrow1_down" title="下移"></a> </li> </ul> <ul class="tr"> <li class="td_width1"><span class="content">bbb.cn</span><input style="display:none;" name="url" id="" class="input_text" min-length="4"  type="url"> </li> <li class="td_width2"><span class="color_red" style="display: none;"></span> <span class="edit hover"><a href="javascript:void(0);" actname="edit"><i class="icon_edit"></i>编辑标签</a><a actname="delete" href="javascript:void(0);"><i class="icon_del"></i>删除标签</a></span></li> <li class="td_width3"><a href="javascript:void(0);" class="arrow1_up" actname="moveUp" title="上移" style="display: none;"></a> <a href="javascript:void(0);" actname="moveDown" class="arrow1_down" title="下移"></a> </li> </ul> <ul class="tr"> <li class="td_width1"><span class="content">ccc.net</span><input style="display:none;" name="url" id="" class="input_text" min-length="4"  type="url"> </li> <li class="td_width2"><span class="color_red" style="display: none;"></span> <span class="edit hover"><a href="javascript:void(0);" actname="edit"><i class="icon_edit"></i>编辑标签</a><a actname="delete" href="javascript:void(0);"><i class="icon_del"></i>删除标签</a></span></li> <li class="td_width3"><a href="javascript:void(0);" class="arrow1_up" actname="moveUp" title="上移" style="display: none;"></a> <a href="javascript:void(0);" actname="moveDown" class="arrow1_down" title="下移"></a> </li> </ul> </div> </div> <div class="layer_btn"> <div class="fl"><b>+</b><a actname="addNewRow" href="javascript:void(0);">添加新标签</a><span class="W_textb">（最多可添加6个标签）</span></div> <a href="javascript:void(0);" actname="save" class="M_btn1"><span>确定</span></a> <a href="javascript:void(0);" actname="cancel" class="M_btn2"><span>取消</span></a></div> </div> <!--/弹层内容--> </div> </form>',
			fun : function(obj){
				dialog = $($(obj.target).attr("rel").toString()).html(this.template);
			}
		},
		msgBoard : {
			template : '<form id="dialogForm" novalidate="novalidate"> <div class="inner"><a class="close" actname="close" href="javascript:void(0);" title="关闭">×</a> <div class="title"><strong>互动标签管理</strong></div> <!--弹层内容--> <div class="wrap"> <div class="tablebox table2"> <div class="thead"> <ul class="tr"> <li class="td_width1">标签名称</li> <li class="td_width3">标签排列位置</li> </ul> </div> <div class="tbody"> <ul class="tr"> <li class="td_width1"><span class="content">测试1</span><input style="display:none;" name="tagName" id="" class="input_text" min-length="1" max-length="6" type="tagName"> </li> <li class="td_width2"><span class="color_red" style="display: none;"></span> <span class="edit hover"><a href="javascript:void(0);" actname="edit"><i class="icon_edit"></i>编辑标签</a><a actname="delete" href="javascript:void(0);"><i class="icon_del"></i>删除标签</a></span></li> <li class="td_width3"><a href="javascript:void(0);" class="arrow1_up" actname="moveUp" title="上移" style="display: none;"></a> <a href="javascript:void(0);" actname="moveDown" class="arrow1_down" title="下移"></a> </li> </ul> <ul class="tr"> <li class="td_width1"><span class="content">测试2</span><input style="display:none;" name="tagName" id="" class="input_text" min-length="1" max-length="6"   type="tagName"> </li> <li class="td_width2"><span class="color_red" style="display: none;"></span> <span class="edit hover"><a href="javascript:void(0);" actname="edit"><i class="icon_edit"></i>编辑标签</a><a actname="delete" href="javascript:void(0);"><i class="icon_del"></i>删除标签</a></span></li> <li class="td_width3"><a href="javascript:void(0);" class="arrow1_up" actname="moveUp" title="上移" style="display: none;"></a> <a href="javascript:void(0);" actname="moveDown" class="arrow1_down" title="下移"></a> </li> </ul> <ul class="tr"> <li class="td_width1"><span class="content">测试3</span><input style="display:none;" name="tagName" id="" class="input_text" min-length="1" max-length="6"   type="tagName"> </li> <li class="td_width2"><span class="color_red" style="display: none;"></span> <span class="edit hover"><a href="javascript:void(0);" actname="edit"><i class="icon_edit"></i>编辑标签</a><a actname="delete" href="javascript:void(0);"><i class="icon_del"></i>删除标签</a></span></li> <li class="td_width3"><a href="javascript:void(0);" class="arrow1_up" actname="moveUp" title="上移" style="display: none;"></a> <a href="javascript:void(0);" actname="moveDown" class="arrow1_down" title="下移"></a> </li> </ul> </div> </div> <div class="layer_btn"> <div class="fl"><b>+</b><a actname="addNewRow" href="javascript:void(0);">添加新标签</a><span class="W_textb">（最多可添加6个标签）</span></div> <a href="javascript:void(0);" actname="save" class="M_btn1"><span>确定</span></a> <a href="javascript:void(0);" actname="cancel" class="M_btn2"><span>取消</span></a></div> </div> <!--/弹层内容--> </div> </form>',
			fun : function(obj){
				dialog = $($(obj.target).attr("rel").toString()).html(this.template);
			}
		}
	};
	var initDialog = function(){
		validator.addNewRule();
		validator.run();
		refreshBtns();
	};
	//弹层
	(function ($) {
		var loading = false;
		var curTrigger;
		var loadTemp = function (obj, key) {

			//TODO ajax请求模板 这里暂时使用setTimeout模拟请求。
			window.setTimeout(function () {
				templateAndFuns[key]["fun"](obj);
				initDialog();
				loading = true;
				curTrigger = trigger[key];
				curTrigger.overlay().load();
			}, 1000);
		};

		var eventFunctions = {
			edit : function(obj){
				var ul = obj.parents("ul");
				var txt = ul.find(".content").hide();
				ul.find(".input_text").val(txt.html()).show().focus();
				ul.find(".edit").hide();
			},
			delete : function(obj){
				if(confirm("确认删除吗？")){
					obj.parents("ul").remove();
					refreshBtns();
				}

			},
			close : function(){
				curTrigger.overlay().close();
			},
			save : function(){
				var rows = dialog.find(".tbody>ul.tr");
				$.each(rows, function(i, row){
					var input = $(row).find(".input_text");
					input.val($(row).find(".content").html());
				});
				var saveData = $("#dialogForm").htmlToJson();
				/*$.ajax({
					url:'/aj/post',
					type : "post",
					onSuccess : function(){},
					data:saveData
				});*/
			},
			cancel : function(){
			},
			addNewRow : function(obj){
				if(validator.checkValid()){
					return;
				}
				var list = dialog.find(".tbody>ul.tr");
				if(list.length >= 6){
					alert("最多允许添加6条数据。");
					return;
				}
				var newTr = list.last().html();
				var last = list.last().after("<ul class='tr'>"+newTr+"</ul>");
				last = last.next();
				last.find(".content").html("");
				refreshBtns();
				validator.run();
				last.find('[actname="edit"]').trigger("click");
			},
			moveUp : function(obj){
				moveTo(obj, 1);
			},
			moveDown : function(obj){
				moveTo(obj, 0);
			}
		};

		//TODO绑定事件。确认，取消，关闭等。
		var bindEvent = function () {
			$("#manageDialog").live("click", {}, function(obj){
				var actEl = obj.target;
				var actName = actEl.getAttribute("actname");
				if(!actName) {
					actEl = actEl.parentNode;
					actName = actEl.getAttribute("actname");
				}
				eventFunctions[actName] && eventFunctions[actName]($(actEl), obj);
			}, "[actname]");
		};
		//创建overlay对象。
		var trigger = {};
		var showDialog = function(id, key){
			trigger[key] = $("#"+id).overlay({
				// some mask tweaks suitable for modal dialogs
				mask:{
					color:'#ebecff',
					loadSpeed:200,
					opacity:0.9
				},
				onBeforeLoad:function (obj) {
					validator.validStatus = false;
					if (!loading) {
						loadTemp(obj, key);
					}
					return loading;
				},
				onLoad : function(){
					loading = false;
				},
				onClose :function(){
					loading = false;
				},
				closeOnClick:false
			});
		};
		$('[rel="#manageDialog"]').each(function(){
			showDialog(this.id, this.id.replace("manage_", ""));
		});
		bindEvent();
	})($);


	//flash播放
	(function ($) {
		var flashPath = "http://player.youku.com/player.php/sid/XNDg2MzA4OTcy/v.swf";
		$("#flashPlayer").flashembed({
			src : flashPath,
			wmode : "transparent"
		});
	})($);

//FrameClient
	FrameClient.addEvent("message", function(){
	});
	//发留言
	(function($){
		var sendBtn = $("#sendMsg");
		var checkBox = $("#sendWeibo");
		var refreshStatus = function(){
			checkBox[0].checked = false;
			sendBtn[0].setAttribute("disabled", "true");
		};
		refreshStatus();
		checkBox.click(function(){
			var checked = this.checked ? "" : "true";
			sendBtn[0].setAttribute("disabled", checked);
		});
		sendBtn.click(function(){
			//TODO ajax 请求发留言

			setTimeout(function (){
			    refreshStatus();
			}, 1000);
			 

		});

	})($);
	//成员管理 拖拽
	(function($){
		var dragArea = $("#manage_account");
		dragArea.sortable({
            revert: true,
			scroll: false,
//			containment : dragArea,
			items : "li",
			helper : "clone"
        });
	})($);
});